-- Lua脚本实现漏桶算法
local key = KEYS[1]
local rate = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])

-- 获取当前存储的请求数和上次更新时间
local requests, last_ts = redis.call("GET", key)
if requests == false then
    requests = 0
    last_ts = 0
else
    requests = tonumber(requests)
    last_ts = tonumber(last_ts)
end

-- 计算当前时间和上次请求的时间间隔
local now = redis.call("TIME")[1]
local allowed, fill_time = capacity, (now - last_ts) * rate
if fill_time > 0 then
    allowed = allowed + fill_time
end

-- 判断是否超出容量，并更新请求数和时间
if requests + 1 > allowed then
    return 0 -- 超出限制
else
    requests = requests + 1
    local expire_time = (now - last_ts) * rate + capacity
    redis.call("SET", key, requests, "PX", math.ceil(expire_time * 1000))
    return 1 -- 未超出限制
end